using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace TTSoft.MyWeb.Models.Repositories
{
	#region using
	using TTSoft.MyWeb.Models;
	using TTSoft.MyWeb.Helpers;
	using System.Web.Security;
	using TTSoft.MyWeb.Models.ViewModels;
	#endregion
	public class NguoiDungRepository
	{
		public int TotalItem { get; set; }
		public List<NguoiDungInfo> SelectAll(string role)
		{
			List<NguoiDungInfo> lstItem = new List<NguoiDungInfo>();
			MembershipUserCollection userCollection = Membership.GetAllUsers();
			foreach (MembershipUser user in userCollection)
			{
				var roleForUser = Roles.GetRolesForUser(user.UserName)[0];
				if (role.ToUpper() == "SUPERADMIN")
				{
					if (roleForUser.ToUpper() != "SUPERADMIN")
					{
						NguoiDungInfo userInfo = new NguoiDungInfo
						{
							BaseInfo = new NguoiDungBaseInfo
							{
								ID = (Guid)user.ProviderUserKey,
								UserName = user.UserName,
								Email = user.Email,
								Role = Roles.GetRolesForUser(user.UserName)[0]
							},
						};
						lstItem.Add(userInfo);
					}
				}
				else if (role.ToUpper() == "ADMIN")
				{
					if (roleForUser.ToUpper() != "SUPERADMIN" && roleForUser.ToUpper() != "ADMIN")
					{
						NguoiDungInfo userInfo = new NguoiDungInfo
						{
							BaseInfo = new NguoiDungBaseInfo
							{
								ID = (Guid)user.ProviderUserKey,
								UserName = user.UserName,
								Email = user.Email,
								Role = Roles.GetRolesForUser(user.UserName)[0]
							},
						};
						lstItem.Add(userInfo);
					}
				}
			}
			TotalItem = lstItem.Count;
			return lstItem;
		}

		public List<NguoiDungInfo> SelectPaging(int page, int pageSize, string role)
		{
			List<NguoiDungInfo> lstItem = new List<NguoiDungInfo>();
			MembershipUserCollection userCollection = Membership.GetAllUsers();
			foreach (MembershipUser user in userCollection)
			{
				var roleForUser = Roles.GetRolesForUser(user.UserName)[0];
				if (role.ToUpper() == "SUPERADMIN")
				{
					if (roleForUser.ToUpper() != "SUPERADMIN")
					{
						NguoiDungInfo userInfo = new NguoiDungInfo
						{
							BaseInfo = new NguoiDungBaseInfo
							{
								ID = (Guid)user.ProviderUserKey,
								UserName = user.UserName,
								Email = user.Email,
								Role = Roles.GetRolesForUser(user.UserName)[0]
							},
						};
						lstItem.Add(userInfo);
					}
				}
				else if (role.ToUpper() == "ADMIN")
				{
					if (roleForUser.ToUpper() != "SUPERADMIN" && roleForUser.ToUpper() != "ADMIN")
					{
						NguoiDungInfo userInfo = new NguoiDungInfo
						{
							BaseInfo = new NguoiDungBaseInfo
							{
								ID = (Guid)user.ProviderUserKey,
								UserName = user.UserName,
								Email = user.Email,
								Role = Roles.GetRolesForUser(user.UserName)[0]
							},
						};
						lstItem.Add(userInfo);
					}
				}
			}
			TotalItem = lstItem.Count;
			if (pageSize > 0)
			{
				int startIndex, itemCount;
				startIndex = (page - 1) * pageSize;
				itemCount = pageSize;
				if (startIndex + itemCount > lstItem.Count)
					itemCount = lstItem.Count - startIndex;
				lstItem = lstItem.GetRange(startIndex, itemCount);
			}

			return lstItem;
		}

		public NguoiDungInfo SelectByUserName(string username)
		{
			var user = Membership.GetUser(username);
			NguoiDungInfo userInfo = new NguoiDungInfo
			{
				BaseInfo = new NguoiDungBaseInfo
				{
					ID = (Guid)user.ProviderUserKey,
					UserName = user.UserName,
					Email = user.Email,
					Role = Roles.GetRolesForUser(user.UserName)[0]
				},
			};
			TotalItem = 1;
			return userInfo;
		}

		public bool Delete(Guid id)
		{
			try
			{
				Membership.DeleteUser(Membership.GetUser(id).UserName, true);
				return true;
			}
			catch
			{
				return false;
			}
		}

		public bool Save()
		{
			try
			{
				DataContext.Instance.SaveChanges();
				return true;
			}
			catch
			{
				return false;
			}
		}

        public List<NguoiDungInfo> RetrieveByID(Guid id)
        {
            var lst = new List<NguoiDungInfo>();
            var baseinfo = new NguoiDungBaseInfo
            {
                ID = id,
                UserName = Membership.GetUser(id).UserName,
                Email = Membership.GetUser(id).Email,
                Role = Roles.GetRolesForUser(Membership.GetUser(id).UserName)[0]
            };
            lst.Add(new NguoiDungInfo { BaseInfo = baseinfo });
            return lst;
        }

		public bool Insert(AddNguoiDungViewModel obj, ref string errorText)
		{
			errorText = "";
			try
			{
				MembershipCreateStatus createStatus;
				MembershipUser newUser = Membership.CreateUser(obj.Info.BaseInfo.UserName, obj.Info.BaseInfo.Password, obj.Info.BaseInfo.Email, "What is your favouritr color?", "Black Or White", true, out createStatus);
				switch (createStatus)
				{
					case MembershipCreateStatus.Success:
						Roles.AddUserToRole(obj.Info.BaseInfo.UserName, obj.Info.BaseInfo.Role);
						break;
					case MembershipCreateStatus.DuplicateUserName:
						errorText = "Người dùng này đã tồn tại, vui lòng nhập vào tên người dùng khác!";
						break;
					case MembershipCreateStatus.DuplicateEmail:
						errorText = "Địa chỉ Email bạn vừa nhập vào đã tồn tại, vui lòng nhập địa chỉ email khác!";
						break;
					case MembershipCreateStatus.InvalidEmail:
						errorText = "Địa chỉ Email không hợp lệ, vui lòng nhập lại.";
						break;
					case MembershipCreateStatus.InvalidPassword:
						errorText = "Mật khẩu phải có độ dài ít nhất 7 kí tự. Trong đó có 1 kí tự Alpha (~@#$%^&*).";
						break;
					default:
						errorText = "Có 1 lỗi gì đó, tài khoản của bạn chưa được khởi tạo.";
						break;
				}
				if (errorText != "")
				{
					return false;
				}
				return true;
			}
			catch
			{
				errorText = "Có 1 lỗi gì đó, tài khoản của bạn chưa được khởi tạo.";
				return false;
			}
		}

		public int GetTotalItem(string role)
		{
			int count = 0;
			MembershipUserCollection userCollection = Membership.GetAllUsers();
			foreach (MembershipUser user in userCollection)
			{
				var roleForUser = Roles.GetRolesForUser(user.UserName)[0];
				if (role.ToUpper() == "SUPERADMIN")
				{
					if (roleForUser.ToUpper() != "SUPERADMIN")
					{
						count++;
					}
				}
				else if (role.ToUpper() == "ADMIN")
				{
					if (roleForUser.ToUpper() != "SUPERADMIN" && roleForUser.ToUpper() != "ADMIN")
					{
						count++;
					}
				}
			}
			return count;
		}

		public int GetTotalPage(string role)
		{
			int RecordCount = GetTotalItem(role);
			int PageSize = WebConfiguration.NumNguoiDungPerPage;
			return (RecordCount / PageSize) + ((RecordCount % PageSize == 0) ? 0 : 1);
		}

	}
}